//
//  WHBaseSanViewController.m
//  WHEasyBizLink
//
//  Created by shengmeng chen on 2024/11/28.
//

#import "WHReSanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "WHScanView.h"
#import "WHDialog.h"

@interface WHReSanViewController ()<AVCapturePhotoCaptureDelegate>
/** 会话对象 */
@property (nonatomic, strong) AVCaptureSession *session;
/** 图层类 */
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic, strong) WHScanView *scanningView;
@property (nonatomic,strong)AVCapturePhotoOutput *captureOutput;

@end

@implementation WHReSanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"重新拍照";
    self.view.backgroundColor = [UIColor blackColor];
    [self setupScanningImage];
    
    // 创建扫描边框
    self.scanningView = [[WHScanView alloc] initWithFrame:self.view.frame outsideViewLayer:self.view.layer];
    [self.view addSubview:self.scanningView];
    __weak __typeof(self) weakSelf = self;
    self.scanningView.clicBtnBlock = ^(UIButton * _Nonnull btn) {
        [weakSelf Captureimage];
    };
}


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.scanningView  addTimer];
}
//页面消失，进入后台不显示该页面，关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear: animated];
    //关闭定时器
    [self.scanningView removeTimer];
}

- (void)setupScanningImage
{
    //1.创建会话层
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
    // Input
    AVCaptureDeviceInput*input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
        
    // Output
    self.captureOutput = [[AVCapturePhotoOutput alloc] init];
    NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
    AVCapturePhotoSettings* outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
    
     [self.captureOutput setPhotoSettingsForSceneMonitoring:outputSettings];
        
        // Session
        self.session = [[AVCaptureSession alloc]init];
        //AVCaptureSessionPresetHigh:实现高质量的视频和音频输出
        [self.session setSessionPreset:AVCaptureSessionPresetHigh];
        // addInput:可称为虽然会话正在运行
        if ([self.session canAddInput:input])
        {
            [self.session addInput:input];
        }
        
        if ([self.session canAddOutput:_captureOutput])
        {
            [self.session addOutput:_captureOutput];
        }
        
    self.previewLayer =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.previewLayer.frame = self.view.bounds;
    [self.view.layer insertSublayer:self.previewLayer atIndex:0];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (self.session) {
               [self.session startRunning];
           }
    });
}

-(void)Captureimage
{
    // 设置照片方向
       AVCaptureConnection *connection = [self.captureOutput connectionWithMediaType:AVMediaTypeVideo];
       if (connection.supportsVideoOrientation) {
           connection.videoOrientation = self.previewLayer.connection.videoOrientation;
       }
       // 创建 AVCapturePhotoSettings
       AVCapturePhotoSettings *photoSettings = [AVCapturePhotoSettings photoSettings];
    if ([self.captureOutput.availablePhotoCodecTypes containsObject:AVVideoCodecTypeJPEG]) {
        NSDictionary *format = @{AVVideoCodecKey: AVVideoCodecTypeJPEG};
           photoSettings = [AVCapturePhotoSettings photoSettingsWithFormat:format];
       }
       // 防抖
       photoSettings.photoQualityPrioritization = YES;
       // 拍照
       [self.captureOutput capturePhotoWithSettings:photoSettings delegate:self];
}

- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhotoSampleBuffer:(nullable CMSampleBufferRef)photoSampleBuffer previewPhotoSampleBuffer:(nullable CMSampleBufferRef)previewPhotoSampleBuffer resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings bracketSettings:(nullable AVCaptureBracketedStillImageSettings *)bracketSettings error:(nullable NSError *)error
{
    NSData *data = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];
    UIImage *image = [UIImage imageWithData:data];
    if (self.reScanFinishBlock) {
        self.reScanFinishBlock(image);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//// 移除定时器
//-(void)dealloc
//{
//    [self.scanningView removeFromSuperview];
//}

@end
